package com.tsingteng.cosfun.ui.cosfun.cosinterface;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;

import com.pili.pldroid.player.IMediaController;

public class MediaProgressController implements IMediaController {
    private IMediaController.MediaPlayerControl mPlayer;
    private Context mContext;
    private ProgressBar progressBar = null;
    private static final int SHOW_PROGRESS = 2;

    public MediaProgressController(Context mContext, ProgressBar progressBar) {
        this.mContext = mContext;
        this.progressBar = progressBar;
        mHandler.sendEmptyMessageDelayed(SHOW_PROGRESS, 100);
    }

    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            long pos;
            switch (msg.what) {
                case SHOW_PROGRESS:
                    if (!mPlayer.isPlaying()) {
                        return;
                    }
                    pos = setProgress();
                    if (pos == -1) {
                        return;
                    }
                    mHandler.sendEmptyMessageDelayed(SHOW_PROGRESS, 100);
                    break;
            }
        }
    };

    @Override
    public void setMediaPlayer(MediaPlayerControl mediaPlayerControl) {
        this.mPlayer = mediaPlayerControl;
    }

    private long setProgress() {
        if (mPlayer == null) {
            return 0;
        }

        long position = mPlayer.getCurrentPosition();
        long duration = mPlayer.getDuration();
        Log.e("test21", "duration=" + duration + "  position=" + position);
        if (progressBar != null) {
            if (duration > 0) {
                long pos = 1000L * position / duration;
                progressBar.setProgress((int) position);
                progressBar.setMax((int) duration);
            }
//            int percent = mPlayer.getBufferPercentage();
//            progressBar.setSecondaryProgress(percent * 10);
        }
        return position;
    }

    @Override
    public void show() {

    }

    @Override
    public void show(int i) {

    }

    @Override
    public void hide() {

    }

    @Override
    public boolean isShowing() {
        return false;
    }

    @Override
    public void setEnabled(boolean b) {

    }

    @Override
    public void setAnchorView(View view) {

    }
}
